package com.example.coffeeseller_2.model.helper.view_helper;

import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.example.coffeeseller_2.R;
import com.example.coffeeseller_2.model.beans.Coffee;
import com.example.coffeeseller_2.model.beans.DealChooseTaste;
import com.example.coffeeseller_2.model.beans.Step;
import com.example.coffeeseller_2.model.beans.Taste;
import com.example.coffeeseller_2.model.beans.TasteInfo;
import com.example.coffeeseller_2.model.contentprovider.MaterialSql;
import com.example.coffeeseller_2.model.listenner.OnTasteSelectedListenner;
import com.example.coffeeseller_2.widget.CiclesView;
import com.example.coffeeseller_2.widget.SeekBarView;

import java.util.List;

/**
 * Created by WH on 2018/9/26.
 * 口味布局辅助类
 */

public class TasteHelper {
    private static String TAG = "TasteHelper";
    public static int avgLength = 50;//seekbar每一小段的平均长度
    private Context context;
    private LinearLayout layout;
    private View content;
    private CiclesView ciclesView;
    private CiclesView ciclesViewTop;
    private SeekBarView seekBarView;
    private TextView tasteName;

    private TasteInfo tasteInfo;
    private Coffee coffee;
    private OnTasteSelectedListenner onTasteSelectedListenner;
    private int maxDragIndex;

    public TasteHelper(Context context, TasteInfo tasteInfo
            , Coffee coffee, OnTasteSelectedListenner onTasteSelectedListenner) {
        this.context = context;
        this.tasteInfo = tasteInfo;
        this.coffee = coffee;
        this.onTasteSelectedListenner = onTasteSelectedListenner;

        init();
    }


    public View getView() {
        return layout;
    }

    /*
* 设置口味不能拖动
* */
    public void setSeekbarEnable() {
        seekBarView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
    }

    private void init() {

        initView();
        initListenner();
        initData();
    }

    /*
    * 初始化口味布局
    * */
    private void initView() {
        layout = new LinearLayout(context);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0);
        params.weight = 0.5f;
        layout.setLayoutParams(params);

        content = LayoutInflater.from(context).inflate(R.layout.include_seekbar_text, null, false);
        layout.addView(content);

        tasteName = (TextView) content.findViewById(R.id.tasteName);
        ciclesView = (CiclesView) content.findViewById(R.id.cicleView);
        ciclesViewTop = (CiclesView) content.findViewById(R.id.cicleViewTop);
        seekBarView = (SeekBarView) content.findViewById(R.id.seekBarView);
        List<Taste> tastes = tasteInfo.getTastes();//getSoftTaste(tasteInfo.getTastes());
        seekBarView.setDatas(tastes);
        seekBarView.setMax((tastes.size() - 1) * avgLength);
        ciclesView.setDatas(tastes);
        ciclesViewTop.setDatas(tastes);
        ciclesViewTop.setMode(1);
        tasteName.setText(tasteInfo.getName());
        DealChooseTaste dealChooseTaste = new DealChooseTaste();
        dealChooseTaste.setTasteInfo(tasteInfo);

        maxDragIndex = getCanMakeCoffeeTasteIndex(tasteInfo, tastes);

        Log.d(TAG, "maxDragIndex = " + maxDragIndex);
        seekBarView.setMaxIndex(maxDragIndex);
    }

    private void initData() {
        List<Taste> tastes = tasteInfo.getTastes();

        Log.d(TAG, "tastes.size =  " + tastes.size());
        if (maxDragIndex + 1 == tastes.size()) {//所有口味都能制作

            seekBarView.setProgressDrawable(ContextCompat.getDrawable(context, R.drawable.layer_seekbar_no_progress));
        } else if (maxDragIndex == 0) {//表示不能拖动，没有口味选择

            seekBarView.setEnabled(false);
            ciclesView.setEnabled(false);
            ciclesView.setAlpha(0.7f);

            seekBarView.setProgressDrawable(ContextCompat.getDrawable(context, R.drawable.layer_seekbar_part_drag));
            seekBarView.setSecondaryProgress(maxDragIndex * avgLength + 2);
//            seekBarView.setProgressDrawable(ContextCompat.getDrawable(homeActivity, R.drawable.layer_seekbar_cannot_drag));
        } else {//表示部分口味能选择

            seekBarView.setProgressDrawable(ContextCompat.getDrawable(context, R.drawable.layer_seekbar_part_drag));
            seekBarView.setSecondaryProgress(maxDragIndex * avgLength + 2);
        }
        ciclesView.setCanDragMaxIndex(maxDragIndex);
        ciclesViewTop.setCanDragMaxIndex(maxDragIndex == 0 ? -1 : maxDragIndex);
        ciclesViewTop.changeSelectedStyle(-1);

        //设置默认选中
        int defaultIndex = getDefaultSelectedIndex(tasteInfo, tastes, maxDragIndex);
        seekBarView.setProgress(defaultIndex * avgLength);
        if (defaultIndex > 0) {
            ciclesViewTop.changeSelectedStyle(defaultIndex - 1);
        }

        ciclesView.changeSelectedStyle(defaultIndex);
    }

    private void initListenner() {
        seekBarView.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                dealProgressChanged(progress, seekBarView, ciclesView, ciclesViewTop, maxDragIndex);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                dealStopTrackingTouch(seekBar, ciclesView, tasteInfo, maxDragIndex);
            }
        });
    }

    /*
   * 获取能够制作咖啡的最大口味的index
   * 要求口味列表按照正序排列:少-> 多
   * */
    private int getCanMakeCoffeeTasteIndex(TasteInfo tasteInfo, List<Taste> tastes) {
        Step step = coffee.getStepList().get(tasteInfo.getStepId());
        for (int i = tastes.size() - 1; i >= 0; i--) {
            Taste taste = tastes.get(i);
            Log.d(TAG, "amount= " + taste.getAmount());
            if (setEnable(step, taste)) {
                return i;
            } else {
                continue;
            }
        }
        return 0;
    }

    /*
     * 根据数据库剩余量计算是否可用
     * */
    private boolean setEnable(Step step, Taste taste) {

        MaterialSql table = new MaterialSql(context);
        String sqlRestMaterial = table.getStorkByMaterialID(step.getMaterial().getMaterialID() + "");

        if (TextUtils.isEmpty(sqlRestMaterial)) {
            return false;
        }
        int sqlRestMaterialInt = Integer.parseInt(sqlRestMaterial);
        float useMaterial = ((float) taste.getAmount() / 100 * step.getAmount());
        Log.d(TAG, "taste.getAmount()= " + taste.getAmount());
        Log.d(TAG, "step.getAmount()= " + step.getAmount());
        Log.d(TAG, "sqlRestMaterialInt= " + sqlRestMaterialInt);
        Log.d(TAG, "useMaterial= " + useMaterial);

        return sqlRestMaterialInt >= useMaterial;
    }

    /*
   * 默认选中接近100的量
   * */
    private int getDefaultSelectedIndex(TasteInfo tasteInfo, List<Taste> tastes, int maxIndex) {

        int curIndex = 0;
        int offset = 0;
        offset = Math.abs(tastes.get(0).getAmount() - 100);
        for (int i = 1; i < maxIndex; i++) {
            Taste taste = tastes.get(i);

            if (offset > Math.abs(taste.getAmount() - 100)) {
                curIndex = i;
                offset = Math.abs(taste.getAmount() - 100);
            }
        }
        if (onTasteSelectedListenner != null) {
            float materialTimeRatio = ((float) tastes.get(curIndex).getAmount()) / 100;
            Log.d(TAG, "materialTimeRatio = " + materialTimeRatio);
            onTasteSelectedListenner.getTasteRadio(materialTimeRatio, tasteInfo.getStepId());
        }

        return curIndex;
    }

    private void dealStopTrackingTouch(SeekBar seekBar, CiclesView ciclesView, TasteInfo tasteInfo, int maxDragIndex) {


        int progress = seekBar.getProgress();
        int index = progress / avgLength;
        float materialTimeRatio = 1f;
        if (index + 1 > ciclesView.getCicleNum()) {
            return;
        }

        if (index > maxDragIndex) {
            seekBar.setProgress(maxDragIndex * avgLength);
            materialTimeRatio = ((float) tasteInfo.getTastes().get(maxDragIndex).getAmount()) / 100;

        } else {
            if (progress >= index * avgLength + avgLength / 2) {
                if (index + 1 >= ciclesView.getCicleNum()) {
                    seekBar.setProgress(seekBar.getMax());
                    materialTimeRatio = ((float) tasteInfo.getTastes().get(index).getAmount()) / 100;
                } else {
                    seekBar.setProgress((index + 1) * avgLength);
                    materialTimeRatio = ((float) tasteInfo.getTastes().get(index + 1).getAmount()) / 100;
                }

            } else {
                seekBar.setProgress(index * avgLength);
                materialTimeRatio = ((float) tasteInfo.getTastes().get(index).getAmount()) / 100;
            }
        }

        if (onTasteSelectedListenner != null) {
            Log.d(TAG, "materialTimeRatio = " + materialTimeRatio);
            onTasteSelectedListenner.getTasteRadio(materialTimeRatio, tasteInfo.getStepId());
        }
    }

    private void dealProgressChanged(int progress, SeekBarView seekBarView, CiclesView ciclesView, CiclesView ciclesViewTop, int maxDragIndex) {

        //不能拖动
        if (maxDragIndex == 0) {
            ciclesViewTop.changeSelectedStyle(-1);
            ciclesView.changeSelectedStyle(-1);
            return;
        }
        int index = progress / avgLength;

        if (progress < 5) {
            ciclesViewTop.changeSelectedStyle(-1);
            ciclesView.changeSelectedStyle(0);
            return;
        }

        if (index > maxDragIndex) {
            seekBarView.setProgress(maxDragIndex * avgLength);
            if (ciclesView.getWhiteCicleIndex() != index) {
                ciclesView.changeSelectedStyle(maxDragIndex);
            }


            ciclesViewTop.changeSelectedStyle(maxDragIndex);
        } else {
            if (ciclesView.getWhiteCicleIndex() != index) {
                ciclesView.changeSelectedStyle(index);
            }
            if (progress - index * avgLength > 5) {
                if (ciclesViewTop.getWhiteCicleIndex() != index) {
                    ciclesViewTop.changeSelectedStyle(index);
                }
            } else {
                ciclesViewTop.changeSelectedStyle(index - 1);
            }
        }
    }

}
